<template>
  <div id="map-container">
    <div class="echarts">
      <div id="map" :style="{width:width+'px',height:height+'px',position: 'absolute'}"></div>
      <img :src="require(`@/assets/images/mapBg.png`)" alt="" style="width: 4.2rem;height: 2.2rem;z-index: -1;transform: scale(0.94, 1.11);margin-top:.24rem" ref="img">

      <div class="drawers">
        <div class="otherPre" @click="clickOthers('非洲')">非洲</div>
        <div class="otherPre" @click="clickOthers('香港')">香港</div>
      </div>
    </div>
    <!-- 弹窗 -->
    <pops ref="pop"></pops>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import json1 from './1.json'
import {bigmapGetAll} from "@/api/home";
import pops from '@/views/components/pop/pops'
export default {
  name: "china2",
  data() {
    return {
      mapName: 'china',
      //散点图展示数据
      toolTipData: [
        /*{
          name: '湖南',
          value: 5,
        },
        {
          name: '安徽',
          value: 3,
        },
        {
          name: '山东',
          value: 80,
        },
        {
          name: '北京',
          value: 5,
        },
        {
          name: '天津',
          value: 5,
        },
        {
          name: '河北',
          value: 5,
        },
        {
          name: '陕西',
          value: 5,
        },
        {
          name: '山西',
          value: 5,
        },
        {
          name: '河南',
          value: 5,
        },
        {
          name: '广东',
          value: 5,
        },
        {
          name: '福建',
          value: 5,
        },
        {
          name: '湖北',
          value: 5,
        },
        {
          name: '重庆',
          value: 5,
        },
        {
          name: '贵州',
          value: 5,
        },
        {
          name: '浙江',
          value: 5,
        },
        {
          name: '江苏',
          value: 5,
        },
        {
          name: '上海',
          value: 5,
        },
        {
          name: '四川',
          value: 35,
        },
        {
          name: '黑龙江',
          value: 13,
        },
        {
          name: '辽宁',
          value: 5,
        },
        {
          name: '吉林',
          value: 5,
        },
        {
          name: '云南',
          value: 27,
        },
        {
          name: '甘肃',
          value: 42,
        },
        {
          name: '广西',
          value: 5,
        },
        {
          name: '海南',
          value: 5,
        },
        {
          name: '台湾',
          value: 5,
        },
        {
          name: '西藏',
          value: 5,
        },
        {
          name: '内蒙古',
          value: 5,
        },
        {
          name: '新疆',
          value: 5,
        },
        {
          name: '青海',
          value: 5,
        },
        {
          name: '宁夏',
          value: 5,
        },
        {
          name: '江西',
          value: 5,
        }*/
      ],
      geoCoordMap: {},
      option: {},
      //列表数据
      dataList: [],
      // bj:'image://${require(`@/assets/mapBg.png`)}',
      height: 0,
      width: 0,
      //地图城市经纬度
      mapFeatures: [
        {name: '黑龙江', cp: [127.9688, 45.368],ename:'heilongjiang'},
        {name: '内蒙古', cp: [110.3467, 41.4899],ename:'neimenggu'},
        {name: "吉林", cp: [125.8154, 44.2584],ename:'jilin'},
        {name: '北京', cp: [116.4551, 40.2539],ename:'beijing'},
        {name: "辽宁", cp: [123.1238, 42.1216],ename:'liaoning'},
        {name: "河北", cp: [114.4995, 38.1006],ename:'hebei'},
        {name: "天津", cp: [117.4219, 39.4189],ename:'tianjin'},
        {name: "山西", cp: [112.3352, 37.9413],ename:'shanxi'},
        {name: "陕西", cp: [109.1162, 34.2004],ename:'shanxi'},
        {name: "甘肃", cp: [103.5901, 36.3043],ename:'gansu'},
        {name: "宁夏", cp: [106.3586, 38.1775],ename:'ningxia'},
        {name: "青海", cp: [101.4038, 36.8207],ename:'qinghai'},
        {name: "新疆", cp: [87.611053, 43.828171],ename:'xinjiang'},
        {name: "西藏", cp: [91.117212, 29.646922],ename:'xizang'},
        {name: "四川", cp: [103.9526, 30.7617],ename:'sichuan'},
        {name: "重庆", cp: [108.384366, 30.439702],ename:'chongqing'},
        {name: "山东", cp: [117.1582, 36.8701],ename:'shandong'},
        {name: "河南", cp: [113.4668, 34.6234],ename:'henan'},
        {name: "江苏", cp: [118.8062, 31.9208],ename:'jiangsu'},
        {name: "安徽", cp: [117.29, 32.0581],ename:'anhui'},
        {name: "湖北", cp: [114.3896, 30.6628],ename:'hubei'},
        {name: "浙江", cp: [119.5313, 29.8773],ename:'zhejiang'},
        {name: "福建", cp: [119.4543, 25.9222],ename:'fujian'},
        {name: "江西", cp: [116.0046, 28.6633],ename:'jiangxi'},
        {name: "湖南", cp: [113.0823, 28.2568],ename:'hunan'},
        {name: "贵州", cp: [106.6992, 26.7682],ename:'guizhou'},
        {name: "云南", cp: [102.9199, 25.4663],ename:'yunnan'},
        {name: "广东", cp: [113.12244, 23.009505],ename:'huangdong'},
        {name: "广西", cp: [108.479, 23.1152],ename:'guangxi'},
        {name: "海南", cp: [110.3893, 19.8516],ename:'hainan'},
        {name: "台湾", cp: [120.702967, 24.123621],ename:'taiwan'},
        {name: '上海', cp: [121.4648, 31.2891],ename:'shanghai'},
        // {name: '香港', cp: [114.1200, 22.2600],ename:'xianggang'},
      ],
      //项目列表
      projectList: [],
    }
  },
  components:{
    pops
  },
  async mounted() {
    await this.getDataList()
    await this.drawEcharts()
    // const viewElem = document.body
    // 监听窗口变化,重绘echarts
    /*const resizeObserver = new ResizeObserver(() => {
      setTimeout(async () => {
        await this.drawEcharts()
      }, 300)
    })
    resizeObserver.observe(viewElem)*/
  },
  methods: {
    clickOthers(params){
      let projectData = this.projectList.filter(item=>{
        return item.province === params
      })
      if(projectData.length>0){
        this.$refs.pop.getShow(projectData[0])
      }else{
        this.$message({
          message: '该省份暂无项目',
          type: 'warning'
        })
      }
    },
    async getDataList() {
      await bigmapGetAll().then(res => {
        if (res.code === 200) {
          this.projectList = this.groupedData(res.data)
          console.log(this.projectList,'projectList')
          this.toolTipData = this.projectList.map(item=>{
            return {name: item.province,value: item.data.length}
          })
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    //根据省份格式化数据分组
    groupedData(v) {
      return v.reduce((result, item) => {
        const province = item.province;
        const group = result.find((group) => group.province === province);
        if (group) {
          group.data.push(item);
        } else {
          result.push({
            province: province,
            data: [item],
          });
        }
        return result;
      }, []);
    },
    drawEcharts() {
      this.width = this.$refs.img.offsetWidth
      this.height = this.$refs.img.offsetHeight
      this.$nextTick(() => {
        this.initEcharts()
      })
    },
    // 初次加载绘制地图
    initEcharts() {
      let myChart = echarts.init(document.getElementById('map'));
      this.mapFeatures.forEach((v) => {
        // 地区名称
        let name = v.name;
        // 地区经纬度
        this.geoCoordMap[name] = v.cp;
      });
      let convertData = (data) => {
        let res = [];
        for (let i = 0; i < data.length; i++) {
          let geoCoord = this.geoCoordMap[data[i].name];
          if (geoCoord) {
            res.push({
              name: data[i].name,
              value: geoCoord.concat(data[i].value),
            });
          }
        }
        return res;
      };
      this.option = {
        backgroundColor: "transparent",
        title: {
          show: false,
          text: "中国地图",
          x: 'center',
          top: "10",
          textStyle: {
            color: "#fff",
            fontFamily: "等线",
            fontSize: 18,
          },
        },
        tooltip: {
          show: false,
          trigger: 'none',
          formatter: (params) => {
            if (typeof params.value[2] == 'undefined') {
              let toolTiphtml = '';
              for (let i = 0; i < this.toolTipData.length; i++) {
                if (params.name === this.toolTipData[i].name) {
                  toolTiphtml += this.toolTipData[i].name + "：" + this.toolTipData[i].value;
                }
              }
              return toolTiphtml;
            } else {
              let toolTiphtml = '';
              for (let i = 0; i < this.toolTipData.length; i++) {
                if (params.name === this.toolTipData[i].name) {
                  toolTiphtml += this.toolTipData[i].name + "：" + this.toolTipData[i].value;
                }
              }
              return toolTiphtml;
            }
          },
          backgroundColor: "#fff",
          borderColor: "#333",
          padding: [5, 10],
          textStyle: {
            color: "#333",
            fontSize: "16"
          }
        },
        animation: {
          duration: 2000,  // 动画时长
          easing: 'linear',  // 缓动效果，可以根据需要调整
          repeat: true  // 重复播放
        },
        geo: [
          {
            layoutCenter: ['50.5%', '50.2%'],//位置
            layoutSize: '175%',//大小
            zlevel: 2,
            show: true,
            map: this.mapName,
            roam: false,
            zoom: 0.97,
            aspectScale: 1,
            label: {
              show: false,
              color: '#fff',
            },
            emphasis: {
              label:{
                show: false,
              },
              itemStyle:{
                borderColor: '#f1870f', // 边框颜色变成黄色
                areaColor: 'rgba(241,135,15,0.2)',
                borderWidth: 3,
              }
            },
            selectedMode: 'radio',
            itemStyle: {
                areaColor: 'transparent',
                borderColor: "transparent",
                borderWidth: 1.5,
                shadowColor: "rgba(63,174,209,0.6)",
                // shadowOffsetY: 10,
                shadowBlur: 20,
            },
            select:{
              itemStyle:{
                borderColor: '#f1870f', // 边框颜色变成黄色
                areaColor: 'rgba(241,135,15,0.2)',
                borderWidth: 3,
              },
              label: {
                show: false,
              },
            }
          },
        ],
        series: [
          //三棱锥
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            geoIndex: 0,
            zlevel: 5,
            label: {
                show: false,
                formatter: (params) => {
                  let name = params.data[2].name
                  let value = params.data[2].value
                  // var text = `{tline|项目个数} : {fline|${value}}`
                  return `{tline|${name}} : {fline|${value}}个`;
                },
                color: '#fff',
                rich: {
                  fline: {
                    // padding: [0, 25],
                    color: '#fff',
                    fontSize: 14,
                    fontWeight: 600
                  },
                  tline: {
                    // padding: [0, 27],
                    color: '#ABF8FF',
                    fontSize: 12,
                  },
                },
            },
            emphasis: {
              label:{
                show:false
              }
            },
            itemStyle: {
              color: '#555',
              borderColor: '#00b5f8',
              opacity: 1
            },
            symbol: json1.img1,
            symbolSize: [12, 12],
            symbolOffset: [0, 10],
            z: 999,
            data: this.scatterData(),
            silent: true,
          },
          // 顶部显示
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            geoIndex: 0,
            zlevel: 5,
            label: {
                show: true,
                formatter: (params) => {
                  let name = params.data[2].name
                  // var text = `{tline|项目个数} : {fline|${value}}`
                  return `{tline|${name}}`;
                },
                color: '#fff',
                rich: {
                  fline: {
                    // padding: [0, 25],
                    color: '#fff',
                    fontSize: 8,
                    fontWeight: 600
                  },
                  tline: {
                    // padding: [0, 27],
                    color: '#fff',
                    fontSize: 8,
                  },
                },
            },
            emphasis: {
              label: {
                show: true
              }
            },
            itemStyle: {
              color: 'transparent',
              borderColor: 'none',
              opacity: 1
            },
            // symbol: this.img2,
            symbolSize: [50, 22],
            symbolOffset: [0, -2],
            z: 999,
            data: this.scatterData(),
            silent: true,
          },
          //涟漪
          {
            name: 'effect',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: convertData(this.toolTipData),
            showEffectOn: 'render',
            rippleEffect: {
              scale: 4,
              brushType: 'stroke',
            },
            label: {
                formatter: '{b}',
                position: 'bottom',
                show: false,
                color: "#fff",
                distance: 8,
            },
            symbol: 'circle',
            symbolSize: [7, 5],
            itemStyle: {
                color: '#00b5f8',
                shadowBlur: 10,
                borderColor: '#fff',
                borderWidth: 1,
                shadowColor: '#00b5f8',
              opacity: 1
            },
            zlevel: 4,
            silent: true
          },
          //连线图
          /*{
            type: 'lines',
            zlevel: 2,
            effect: {
              show: true,
              period: 4, //箭头指向速度，值越小速度越快
              trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长
              symbol: 'arrow', //箭头图标
              symbolSize: 5, //图标大小
            },
            lineStyle: {
              color: '#00faff',
              width: 1, //尾迹线条宽度
              opacity: 0.7, //尾迹线条透明度
              curveness: .3 //尾迹线条曲直度
            },
            data: this.convertData()
          },*/
        ],
      };

      myChart.setOption(this.option);
      //点击事件
      myChart.on('click', (params) => {
        console.log(params,'params')
        event.stopPropagation();
        let projectData = this.projectList.filter(item=>{
          return item.province === params.name
        })
        if(projectData.length>0){
          this.$refs.pop.getShow(projectData[0])
        }else{
          this.$message({
            message: '该省份暂无项目',
            type: 'warning'
          })
        }
      });
      // 监听窗口大小变化
      /*window.addEventListener('resize', function () {
        myChart.resize()// 调用图表的 resize 方法
      });*/
    },
    // 柱状体的顶部
    scatterData() {
      return this.toolTipData.map((item) => {
        if (this.geoCoordMap[item.name]) {
          return [this.geoCoordMap[item.name][0], this.geoCoordMap[item.name][1] + 2, item]
        }
      })
    },
    convertData () {
      let res = [];
      this.toolTipData.forEach((item) => {
        let fromCoord = this.geoCoordMap[item.name];
        let toCoord = [116.4551, 40.2539];
        if (fromCoord && toCoord) {
          res.push([
            {
              coord: toCoord,
              value: item.value,
            },
            {
              coord: fromCoord,
            },
          ]);
        }
      })
      // console.log(res)
      return res;
    },
  }
}
</script>

<style scoped lang="scss">
#map-container {
  width: 100%;
  height: 100%;
  //overflow: hidden;
  position: relative;
  left: 0;
  z-index: 12;
  .echarts {
    width: 100%;
    height: 100%;
    //background: #fff;
    transform-style: preserve-3d;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
    .drawers{
      position: absolute;
      right: 0;
      bottom: 20%;
      color: #fff;
      .otherPre{
        width: 100px;
        height: 36px;
        background: url("./assets/butbg.png") no-repeat;
        background-size: 100% 100%;
        text-align: center;
        line-height: 36px;
        cursor: pointer;
      }
    }
  }
}
</style>
